<template>
  <div class="chat-panel">
    <!-- 顶部栏：模型->角色->提示词，无参数配置 -->
    <header class="chat-header">
      <a-space>
        <img src="/logo.png" class="chat-logo" />
        <a-select v-model:value="currentModel" :options="modelOptions" style="width: 140px" @change="onModelChange" placeholder="选择模型" />
        <a-select v-model:value="currentRole" :options="roleOptions" style="width: 140px" @change="onRoleChange" placeholder="选择角色" />
        <a-select
          v-model:value="selectedPrompts"
          :options="promptOptions"
          mode="multiple"
          style="width: 220px"
          placeholder="选择提示词"
          allowClear
        />
        <a-button @click="newSession" type="primary">新对话</a-button>
      </a-space>
    </header>

    <!-- 主体区：消息+输入框整体垂直居中 -->
    <div class="chat-main">
      <main class="chat-history" ref="history">
        <div v-for="msg in messages" :key="msg.id" :class="['chat-bubble', msg.from]">
          <a-comment
            :author="msg.from === 'user' ? '我' : 'AI'"
            :avatar="msg.from === 'user' ? userAvatar : aiAvatar"
            :datetime="msg.time"
          >
            <template #content>
              <div v-if="msg.from === 'ai'" class="markdown-body" v-html="msg.rendered || msg.content" />
              <span v-else>{{ msg.content }}</span>
            </template>
          </a-comment>
        </div>
        <a-spin v-if="loading" tip="AI思考中..." />
      </main>
      <footer class="chat-input-area">
        <a-textarea
          v-model:value="input"
          :auto-size="{ minRows: 2, maxRows: 6 }"
          @keydown.enter="handleEnter"
          placeholder="请输入你的问题，Enter发送，Shift+Enter换行"
        />
        <a-button type="primary" @click="send" :loading="loading">发送</a-button>
      </footer>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted,reactive} from 'vue';
import { message as $message } from 'ant-design-vue';
import { aiApi } from '/@/api/business/ai/ai-api';
import { aiRoleApi } from '/@/api/business/ai/ai-role-api';
import MarkdownIt from 'markdown-it';
import VueMarkdownIt from 'vue3-markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

const userAvatar = '/public/favicon.ico';
const aiAvatar = '/public/logo.png?v=' + Date.now();

const currentModel = ref('');
const modelOptions = ref([]); // [{label, value}]
const currentRole = ref('');
const roleOptions = ref([]); // [{label, value}]
const selectedPrompts = ref([]); // 多选
const promptOptions = ref([]); // [{label, value}]

const messages = ref([]);
const input = ref('');
const loading = ref(false);

function stripDataPrefix(str) {
  // 去除每行开头的data:前缀和多余空白
  return (str || '').replace(/^data:\s*/gm, '').replace(/\n{2,}/g, '\n');
}

const md = new MarkdownIt({
  html: true, // 允许渲染 HTML 标签
  linkify: true,
  typographer: true,
  breaks: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre class="hljs"><code>' + hljs.highlight(str, { language: lang, ignoreIllegals: true }).value + '</code></pre>';
      } catch (__) {}
    }
    return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
  }
});

onMounted(() => {
  loadModelOptions();
});

function loadModelOptions() {
  aiApi.getModelList().then(res => {
    modelOptions.value = (res.data || []).filter(m => m.enable).map(m => ({
      label: m.displayName || m.modelName,
      value: m.modelName,
    }));
    if (!currentModel.value && modelOptions.value.length) {
      currentModel.value = modelOptions.value[0].value;
      onModelChange(currentModel.value);
    }
  });
}

function onModelChange(model) {
  aiRoleApi.getRoleList(model).then(res => {
    // 假设返回的数据结构为 [{roleName, id, prompts: [{alias, ...}]}]
    // 先将角色列表提取出来
    const roles = (res.data || []).map(r => ({
      label: r.roleName,
      value: r.id,
      prompts: r.prompts || [],
    }));
    roleOptions.value = roles;
    currentRole.value = roles.length ? roles[0].value : '';
    // 默认选中第一个角色时，刷新提示词
    if (roles.length) {
      promptOptions.value = roles[0].prompts.map(p => ({ label: p.alias, value: p.alias }));
      selectedPrompts.value = [];
    } else {
      promptOptions.value = [];
      selectedPrompts.value = [];
    }
  });
}

function onRoleChange(roleId) {
  aiRoleApi.getPromptList(roleId).then(res => {
    promptOptions.value = (res.data || []).map(p => ({
      label: p.alias,
      value: p.alias,
    }));
    selectedPrompts.value = [];
  });
}

function newSession() {
  messages.value = [];
  input.value = '';
  $message.success('已开启新对话');
}
function handleEnter(e) {
  if (!e.shiftKey) {
    e.preventDefault();
    send();
  }
}
async function send() {
  if (!input.value.trim()) {
    $message.warning('请输入内容');
    return;
  }
  const userMsg = {
    id: Date.now(),
    from: 'user',
    content: input.value,
    time: new Date().toLocaleString(),
  };
  messages.value.push(userMsg);
  loading.value = true;
  nextTick(() => scrollToBottom());

   // 新增AI消息占位，确保响应式
   const aiMsg = reactive({
    id: Date.now() + 1,
    from: 'ai',
    content: '',
    rendered: '',
    time: new Date().toLocaleString(),
  });
  messages.value.push(aiMsg);
  
  try {
    await aiApi.chatStream({
      modelName: currentModel.value,
      prompt: input.value,
      params: {},
      roleId: currentRole.value,
      promptIds: selectedPrompts.value,
    }, (chunk) => {
      const cleanChunk = stripDataPrefix(chunk);
      aiMsg.content += cleanChunk;
      aiMsg.rendered = md.render(aiMsg.content);
      // 强制触发响应式更新
      aiMsg.content = aiMsg.content;
      aiMsg.rendered = aiMsg.rendered;
      nextTick(() => scrollToBottom());
      console.log('onMessage', cleanChunk);
    });
  } catch (e) {
    aiMsg.content += '\n[AI请求失败]';
    aiMsg.rendered = md.render(aiMsg.content);
    $message.error('AI请求失败');
  } finally {
    loading.value = false;
    input.value = '';
  }
}
function scrollToBottom() {
  const el = document.querySelector('.chat-history');
  if (el) el.scrollTop = el.scrollHeight;
}
</script>

<style scoped lang="less">
.chat-panel {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f7f8fa;
  .chat-header {
    padding: 16px 32px;
    border-bottom: 1.5px solid #f0f0f0;
    background: #fff;
    z-index: 2;
  }
  .chat-logo {
    height: 32px;
    margin-right: 12px;
  }
  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    min-height: 0;
    padding: 0;
  }
  .chat-history {
    width: 100%;
    max-width: 540px;
    min-width: 340px;
    min-height: 320px;
    max-height: 60vh;
    margin: 24px 0 0 0;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 4px 24px 0 #e6e6e6;
    padding: 24px 20px 12px 20px;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    gap: 12px;
  }
  .chat-bubble {
    display: flex;
    flex-direction: row;
    align-items: flex-end;
    margin-bottom: 0;
  }
  .chat-bubble.user {
    justify-content: flex-end;
    background: #e6f7e6;
    border-radius: 14px 14px 4px 14px;
    color: #222;
    font-size: 16px;
    padding: 10px 18px;
    margin: 4px 0;
    box-shadow: 0 2px 8px #e6fae6;
    word-break: break-word;
  }
  .chat-bubble.ai {
    justify-content: flex-start;
    background: #f7faff;
    border-radius: 16px 16px 16px 6px;
    color: #222;
    font-size: 16px;
    padding: 14px 20px;
    margin: 6px 0;
    box-shadow: 0 2px 12px #e6f0fa;
    word-break: break-word;
    font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
    .markdown-body {
      font-size: 16px;
      line-height: 1.8;
      code {
        background: #f6f8fa;
        color: #c7254e;
        padding: 2px 4px;
        border-radius: 4px;
      }
      pre code {
        background: #282c34;
        color: #fff;
        padding: 10px;
        border-radius: 8px;
        font-size: 15px;
      }
      table {
        border-collapse: collapse;
        width: 100%;
      }
      th, td {
        border: 1px solid #eaeaea;
        padding: 6px 12px;
      }
      blockquote {
        color: #6a737d;
        border-left: 4px solid #dfe2e5;
        padding: 0 1em;
        margin: 0.5em 0;
        background: #f8f8f8;
      }
    }
  }
  .chat-input-area {
    width: 100%;
    max-width: 540px;
    margin: 12px 0 24px 0;
    display: flex;
    gap: 8px;
    padding: 12px 16px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px 0 #f0f1f2;
    border: 1px solid #f0f0f0;
  }
}
</style>